package data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Date;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class StockData {

	synchronized public static String getstockData(String address) throws IOException{
		URL url = new URL(address);
		BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
		String s = new String();
		if((s=reader.readLine())!=null){
			return s;
		}
		return null;
	}
	
	public static TimeStock getTimeStock(String code) throws IOException {
		TimeStock ts = new TimeStock();
		String url = "http://hq.sinajs.cn/list=" + code;
		String string = getstockData(url);
		if(string==null){
			return null;
		}
		string = string.substring(string.indexOf("\"") + 1);
		string = string.substring(0, string.indexOf("\""));
		String[] s = string.split(",");
		if(s.length<32){
			return null;
		}
		ts.setCode(code);
		ts.setStockName(s[0]);
		ts.setBeginPrice(new BigDecimal(s[1]));
		ts.setPreDayPrice(new BigDecimal(s[2]));
		ts.setCurPrice(new BigDecimal(s[3]));
		ts.setMaxPrice(new BigDecimal(s[4]));
		ts.setMinPrice(new BigDecimal(s[5]));
		ts.setCurBuyPrice(new BigDecimal(s[6]));
		ts.setCurSalePrice(new BigDecimal(s[7]));
		ts.setQty((int)(Integer.parseInt(s[8])));
		ts.setAmount(new BigDecimal(s[9]));
		ts.setFirstBuyqty(Integer.parseInt(s[10]));
		ts.setFirstBuyPrice(new BigDecimal(s[11]));
		ts.setSecondBuyqty(Integer.parseInt(s[12]));
		ts.setSecondBuyPrice(new BigDecimal(s[13]));
		ts.setThirdBuyqty(Integer.parseInt(s[14]));
		ts.setThirdBuyPrice(new BigDecimal(s[15]));
		ts.setForthBuyqty(Integer.parseInt(s[16]));
		ts.setForthBuyPrice(new BigDecimal(s[17]));
		ts.setFifthBuyqty(Integer.parseInt(s[18]));
		ts.setFifthBuyPrice(new BigDecimal(s[19]));
		ts.setFirstSaleqty(Integer.parseInt(s[20]));
		ts.setFirstSalePrice(new BigDecimal(s[21]));
		ts.setSecondSaleqty(Integer.parseInt(s[22]));
		ts.setSecondSalePrice(new BigDecimal(s[23]));
		ts.setThirdSaleqty(Integer.parseInt(s[24]));
		ts.setThirdSalePrice(new BigDecimal(s[25]));
		ts.setForthSaleqty(Integer.parseInt(s[26]));
		ts.setForthSalePrice(new BigDecimal(s[27]));
		ts.setFifthSaleqty(Integer.parseInt(s[28]));
		ts.setFifthSalePrice(new BigDecimal(s[29]));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			ts.setDate(new Date(sdf.parse(s[30]).getTime()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String[] time = s[31].split(":");
		Time t = new Time(Integer.parseInt(time[0]), Integer.parseInt(time[1]), Integer.parseInt(time[2]));
		ts.setTime(t);

		return ts;
	}

}
